package com.ruoyi.miniapp.controller;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.InnerAuth;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.miniapp.api.domain.MiniappDept;
import com.ruoyi.miniapp.api.domain.MiniappRole;
import com.ruoyi.miniapp.api.domain.MiniappUser;
import com.ruoyi.miniapp.service.*;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 微信用户Controller
 *
 * @author ruoyi
 * @date 2023-09-22
 */
@RestController
@RequestMapping("/user")
public class MiniappUserController extends BaseController
{
    @Autowired
    private IMiniappUserService miniappUserService;
    @Autowired
    private IMiniappDeptService miniappDeptService;
    @Autowired
    private IMiniappRoleService miniappRoleService;
    @Autowired
    private IMiniappPostService iMiniappPostService;
    @Autowired
    private IMiniappPermissionService iMiniappPermissionService;

    /**
     * 查询微信用户列表
     */
    @RequiresPermissions("miniapp:user:list")
    @GetMapping("/list")
    public TableDataInfo list(MiniappUser miniappUser)
    {
        startPage();
        List<MiniappUser> list = miniappUserService.selectMiniappUserList(miniappUser);
        return getDataTable(list);
    }

    /**
     * 导出微信用户列表
     */
    @RequiresPermissions("miniapp:user:export")
    @Log(title = "微信用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MiniappUser miniappUser)
    {
        List<MiniappUser> list = miniappUserService.selectMiniappUserList(miniappUser);
        ExcelUtil<MiniappUser> util = new ExcelUtil<MiniappUser>(MiniappUser.class);
        util.exportExcel(response, list, "微信用户数据");
    }


    /**
     * 新增微信用户
     */
    @RequiresPermissions("miniapp:user:add")
    @Log(title = "微信用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MiniappUser miniappUser)
    {
        if (!miniappUserService.checkUserNameUnique(miniappUser))
        {
            return error("新增用户'" + miniappUser.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(miniappUser.getPhonenumber()) && !miniappUserService.checkPhoneUnique(miniappUser))
        {
            return error("新增用户'" + miniappUser.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(miniappUser.getEmail()) && !miniappUserService.checkEmailUnique(miniappUser))
        {
            return error("新增用户'" + miniappUser.getUserName() + "'失败，邮箱账号已存在");
        }
        miniappUser.setCreateBy(SecurityUtils.getUsername());
        miniappUser.setPassword(SecurityUtils.encryptPassword(miniappUser.getPassword()));
        return toAjax(miniappUserService.insertMiniappUser(miniappUser));
    }

    /**
     * 修改微信用户
     */
    @RequiresPermissions("miniapp:user:edit")
    @Log(title = "微信用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MiniappUser miniappUser)
    {
        miniappUserService.checkUserDataScope(miniappUser.getUserId());
        if (!miniappUserService.checkUserNameUnique(miniappUser))
        {
            return error("修改用户'" + miniappUser.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(miniappUser.getPhonenumber()) && !miniappUserService.checkPhoneUnique(miniappUser))
        {
            return error("修改用户'" + miniappUser.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(miniappUser.getEmail()) && !miniappUserService.checkEmailUnique(miniappUser))
        {
            return error("修改用户'" + miniappUser.getUserName() + "'失败，邮箱账号已存在");
        }
        miniappUser.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(miniappUserService.updateMiniappUser(miniappUser));
    }

    /**
     * 删除微信用户
     */
    @RequiresPermissions("miniapp:user:remove")
    @Log(title = "微信用户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId()))
        {
            return error("当前用户不能删除");
        }
        return toAjax(miniappUserService.deleteMiniappUserByIds(userIds));
    }

    /**
     * 获取部门树列表
     */
    @RequiresPermissions("miniapp:user:list")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(MiniappDept miniappDept)
    {
        return success(miniappDeptService.selectDeptTreeList(miniappDept));
    }


    /**
     * 根据用户编号获取详细信息
     */
    @RequiresPermissions("miniapp:user:query")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        miniappUserService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<MiniappRole> roles = miniappRoleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", iMiniappPostService.selectPostAll());
        if (StringUtils.isNotNull(userId))
        {
            MiniappUser miniappUser = miniappUserService.selectMiniappUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, miniappUser);
            ajax.put("postIds", iMiniappPostService.selectPostListByUserId(userId));
            ajax.put("roleIds", miniappUser.getRoles().stream().map(MiniappRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }


    /**
     * 状态修改
     */
    @RequiresPermissions("miniapp:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody MiniappUser miniappUser)
    {
        miniappUserService.checkUserAllowed(miniappUser);
        miniappUserService.checkUserDataScope(miniappUser.getUserId());
        miniappUser.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(miniappUserService.updateUserStatus(miniappUser));
    }


    /**
     * 重置密码
     */
    @RequiresPermissions("miniapp:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody MiniappUser miniappUser)
    {
        miniappUserService.checkUserAllowed(miniappUser);
        miniappUserService.checkUserDataScope(miniappUser.getUserId());
        miniappUser.setPassword(SecurityUtils.encryptPassword(miniappUser.getPassword()));
        miniappUser.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(miniappUserService.resetPwd(miniappUser));
    }
    @InnerAuth
    @PostMapping("/info/save")
    public R<Boolean> save(MiniappUser miniappUser){
        return  R.ok(miniappUserService.insertMiniappUser(miniappUser) > 0);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        MiniappUser miniappUser = miniappUserService.selectMiniappUserById(SecurityUtils.getUserId());
        // 角色集合
        Set<String> roles = iMiniappPermissionService.getRolePermission(miniappUser);
        // 权限集合
        Set<String> permissions = iMiniappPermissionService.getMenuPermission(miniappUser);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", miniappUser);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    @InnerAuth
    @PostMapping("/info/{username}")
    public  R<LoginUser> info(@PathVariable("username") String username){
        MiniappUser miniappUser = miniappUserService.getInfoByName(username);
        if (StringUtils.isNull(miniappUser))
        {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = iMiniappPermissionService.getRolePermission(miniappUser);
        // 权限集合
        Set<String> permissions = iMiniappPermissionService.getMenuPermission(miniappUser);
        LoginUser wxUser = new LoginUser();
        wxUser.setMiniappUser(miniappUser);
        wxUser.setRoles(roles);
        wxUser.setPermissions(permissions);
        return R.ok(wxUser);
    }
}
